<script setup>
import { ref, onMounted, watch, toRefs } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  data: {
    type: Array,
    required: true
  }
})

const { data } = toRefs(props)

const chartRef = ref(null)
let chart = null

const initChart = () => {
  if (chart) {
    chart.dispose()
  }

  chart = echarts.init(chartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: data.value?.map((item) => item.date),
      boundaryGap: false
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [
      {
        data: data.value?.map((item) => item.count),
        type: 'line',
        smooth: true,
        areaStyle: {
          opacity: 0.2
        },
        lineStyle: {
          width: 3
        },
        itemStyle: {
          color: '#3498db'
        }
      }
    ],
    grid: {
      left: '3%',
      right: '6%',
      bottom: '3%',
      containLabel: true
    }
  }

  chart.setOption(option)
}

watch(
  () => data,
  () => {
    initChart()
  },
  { deep: true }
)

onMounted(() => {
  initChart()
  window.addEventListener('resize', () => {
    chart?.resize()
  })
})
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 300px"></div>
</template>
